package com.xmy.cultivate.controller;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.annotaion.RepeatSubmit;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.response.ArrivalRate;
import com.xmy.cultivate.entity.response.Reconciliation;
import com.xmy.cultivate.entity.response.UserSort;
import com.xmy.cultivate.entity.views.ResidueStatics;
import com.xmy.cultivate.entity.views.StudentClassLogRep;
import com.xmy.cultivate.feign.erp_admin.IAdminFeignClient;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.respons.AssignMoney;
import com.xmy.cultivate.respons.ResSchoolDate;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * <p>
 * 记上课
 * </p>
 *
 * @author min
 * @since 2022-11-01
 */
@RestController
@RequestMapping("/api/orderApply")
public class OrderApplyController extends BaseController {

    @Autowired
    IOrderApplyService iOrderApplyService;
    @Autowired
    private IAdminFeignClient iAdminFeignClient;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    IStudentGradeService iStudentGradeService;

    @Autowired
    IOrderDetailService iOrderDetailService;

    @GetMapping("/reconciliationRate")
    public Result reconciliationRate(@RequestParam Map reMap) {
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");

        List<Reconciliation> reconciliations = iOrderApplyService.reconciliationRate(yearPart, quarterNum, subjectsId, startDate, endDate);

        return new Result(Code.OK, reconciliations, Code.GET_OK_MSG);
    }

    @GetMapping("/reconciliationDetails")
    public Result reconciliationDetails(@RequestParam Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        Page<Reconciliation> iPage = new Page<>(pageNum, pageSize);

        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");
        String schoolId = (String) reMap.get("schoolId");
        String status = (String) reMap.get("status");
        iOrderApplyService.reconciliationDetails(iPage, yearPart, quarterNum, subjectsId, startDate, endDate, schoolId, status);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }

    @PostMapping()
    @RequiresPermissions(value = "home:edu:renew:order:save")
    @RepeatSubmit(expireSeconds = 30)
    public Result save(@RequestBody OrderApply orderApply) throws Exception {
        Result rs;
        try {
            orderApply.setSignType(3);//拉卡拉支付
            rs=  iAdminFeignClient.orderSave(orderApply);
        }catch (Exception e){
            rs = new Result(Code.ERROR,"", "系统更新中，请1分钟后再提交");
        }

        return rs;
    }
    /**
     * 获取报读课程
     *
     * @param
     * @return
     */
    @GetMapping("/getLessonByStuInfoId/{studentId}")
    public Result getLessonByStuInfoId(@PathVariable(value = "studentId") Long studentId,
                                       @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType) {
        return iAdminFeignClient.applyGetLessonByStuInfoId(studentId,lessonType);
    }

    @GetMapping("/checkCourse")
    public Result checkCourse(@RequestParam Map<String, String> reMap,
                              @RequestParam(value = "schoolId", defaultValue = "") Long schoolId,
                              @RequestParam(value = "yearClassIdList", defaultValue = "") String[] yearClassIdList,
                              @RequestParam(value = "subjectsId", defaultValue = "") String[] subjectsIdArr,
                              @RequestParam(value = "quarterNumList", defaultValue = "") String[] quarterNumList,
                              @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType) {
        Result rs;
        try {
            rs = iAdminFeignClient.applyCheckCourse(reMap,schoolId,yearClassIdList,subjectsIdArr,quarterNumList,lessonType);
        }catch (Exception e){
            rs = new Result(Code.ERROR,"", "系统更新中，请1分钟后再使用");
        }
        return rs;
    }

    @GetMapping("/dict")
    public Result dict(@RequestParam Map reMap) {
        return iAdminFeignClient.getDict(reMap);
    }


    /**
     * 获取学生报读科目的校区
     * @return
     */
    @GetMapping("/getApplySubjectsSchoolId")
    public Result getApplySubjectsSchoolId(@RequestParam("studentId") Long studentId,
                                           @RequestParam("subjectsId") Long subjectsId
                                           ){
        Quarter quarter = iQuarterService.getNowQuarter();
        QueryWrapper<StudentGrade> studentGradeQueryWrapper= new QueryWrapper<>();
        studentGradeQueryWrapper.eq("year_part", quarter.getYearPart());
        studentGradeQueryWrapper.eq("quarter_num", quarter.getNum());
        studentGradeQueryWrapper.eq("student_id", studentId);
        studentGradeQueryWrapper.eq("subjects_id", subjectsId);
        studentGradeQueryWrapper.ne("status", 3);
        studentGradeQueryWrapper.eq("is_last",1);
        studentGradeQueryWrapper.eq("lesson_type",1);
        studentGradeQueryWrapper.orderByDesc("id");
        studentGradeQueryWrapper.last("limit 1");
        StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
        Long schoolId = null;
        if (Objects.isNull(studentGrade)){
            QueryWrapper<OrderDetail> orderDetailQueryWrapper= new QueryWrapper<>();
            orderDetailQueryWrapper.eq("year_part", quarter.getYearPart());
            orderDetailQueryWrapper.eq("quarter_num", quarter.getNum());
            orderDetailQueryWrapper.eq("student_id", studentId);
            orderDetailQueryWrapper.eq("subjects_id", subjectsId);
            orderDetailQueryWrapper.ne("status", 2);
            orderDetailQueryWrapper.eq("lesson_type",1);
            orderDetailQueryWrapper.and(i->i.gt("use_course_count",0).or(j->j.gt("residue_course_count",0)));
            orderDetailQueryWrapper.orderByDesc("id");
            orderDetailQueryWrapper.last("limit 1");
            OrderDetail orderDetail = iOrderDetailService.getOne(orderDetailQueryWrapper);
            if (!Objects.isNull(orderDetail)){
                schoolId = orderDetail.getSchoolId();
            }
        }else {
            schoolId = studentGrade.getSchoolId();
        }
        Map<String,Object> map = new HashMap<>();
        map.put("schoolId",schoolId);
        return new Result(Code.OK, map, Code.GET_OK_MSG);
    }


    @PostMapping("/isAddPass")
    public Result isAddPass(@RequestBody OrderApply orderApply) {
        return  iAdminFeignClient.isAddPass(orderApply);
    }


}
